@extends('layouts.app')

@section('title', '数据统计')

@section('css-import')
<style type="text/css">
.form-input-control{
	margin-bottom: 20px;
}
.loadCardBackground{
	width: 350px;
	display: block;
	margin:15px;
}
.card-list,.card-relist{
	margin-top:10px;
	cursor:move;
}
.box{
	text-align: center;
	overflow: hidden;
	position: relative;
}
.box:before{
	content: "";
	width: 0;
	height: 100%;
	background: #000;
	padding: 14px 18px;
	position: absolute;
	top: 0;
	left: 50%;
	border-radius: 3%;
	/*opacity: 0;*/
	width: 100%;
	left: 0;
	opacity: 0.5;
	transition: all 500ms cubic-bezier(0.47, 0, 0.745, 0.715) 0s;
}

.box img{
	width: 100%;
	height: auto;
}
.box .box-content{
	width: 100%;
    padding: 0px 18px; 
    color: #fff;
    position: absolute;
    top: 22%;
    left: 0;
}
.box .title{
	font-size: 22px;
	font-weight: 600;
	line-height: 30px;
	text-transform: uppercase;
	margin: 0;
	transition: all 0.5s ease 0s;
	transition-delay: 0.7s;
}
.box .post{
	font-size: 14px;
	text-transform: capitalize;
	transition: all 0.5s ease 0s;
	transition-delay: 0.7s;
}

.box .icon{
	padding: 0;
	margin: 0;
	list-style: none;
	margin-top: 15px;
}
.box .icon li{
	display: inline-block;
}
.box .icon li a{
	display: block;
	width: 40px;
	height: 40px;
	line-height: 40px;
	border-radius: 50%;
	background: #f74e55;
	font-size: 1.9rem;
	font-weight: 700;
	color: #fff;
	margin-right: 5px;
}

@media screen and (max-width: 1440px){
	.box .title {
		font-size: 15px;
	}
	.box .post {
    	font-size: 10px;
	}
	.box .icon {
		margin-top: 6px;
	}
	.box .icon li a {
		width: 30px;
    	height: 30px;
    	font-size: 10px;
    	line-height: 34px;
	}
	.box .box-content {
		top: 11%;
	}
	.range_sign{
		position: absolute;
	    width: 65px;
	    top: -11px;
	    left: -5px;
	    background: #ad6c6c;
	}

	.range_sign span{
		font-size: 12px;
	}
}
.monochrome{
	-webkit-filter: grayscale(80%); 
    -moz-filter: grayscale(80%); 
    -ms-filter: grayscale(80%); 
    -o-filter: grayscale(80%); 
    filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);  
    _filter:none; 
}
.card-list:hover .monochrome{
	-webkit-filter: grayscale(0%); 
    -moz-filter: grayscale(0%); 
    -ms-filter: grayscale(0%); 
    -o-filter: grayscale(0%); 
    filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=0);  
    _filter:none; 
    -webkit-transition: filter .5s; 
    -moz-transition: filter .5s; 
    -ms-transition: filter .5s; 
    -o-transition: filter .5s; 
    transition: filter .5s;

}

.card-list:hover .box:before{
	-webkit-transition: filter .5s; 
    -moz-transition: filter .5s; 
    -ms-transition: filter .5s; 
    -o-transition: filter .5s; 
    transition: filter .5s;
	opacity: 0;
}
.range_sign{
    position: absolute;
    min-width: 60px;
    max-width: 120px;
    top: 0px;
    background: #ad6c6c;
    left: 0px;
}

.range_sign span{
	font-size: 12px;
}

.range_sign_ul{
	padding:0;
	margin:-18px;
	list-style:none;
	float: left;
}


.range_sign_li{
	min-width: 60px;
    max-width: 85px;
    background: #ad6c6c;
    margin-top: 9px;
}

.range_sign_li span{
	font-size: 12px;
}

</style>
@endsection

@section('content-fluid')
<div class="row">
	<ul class="nav nav-pills" style="float:left;">
	  <li role="presentation" class="orderall">
	  	<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
	      商圈 <span class="caret"></span>
	    </a>
	    <ul class="dropdown-menu">
	    	@foreach($circles as $k=>$v)
	      <li role="presentation" class="circle_select" data-id="{{$v->circle_id}}"><a href="/manageCard?circle_id={{$v->circle_id}}">{{$v->circle_name}}</a></li>
	      @endforeach
	    </ul>
	  </li>
	  <!-- <li role="presentation" class="orderall">
	  	<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
	      城市 <span class="caret"></span>
	    </a>
	    <ul class="dropdown-menu">
	      <li role="presentation" class=""><a href="">打包</a></li>
	      <li role="presentation" class=""><a href="">不打包</a></li>
	    </ul>
	  </li> -->
	  <li role="presentation" class="orderall"><a href="/manageCard">全部</a></li>
	</ul>
</div>
<div class="row">

	<!-- BASIC TABLE -->
	@if($cards->count()>0)
	<div class="panel">
		
		<div class="panel-heading">
			<h3 class="panel-title">在售饭卡</h3>
		</div>

		<div class="panel-body" id="cards_list">

		    @foreach($cards as $k=>$v)
		    <div class="col-md-4 col-sm-6 card-list" id="card-sort{{$k}}" drag-id="{{$sort[$v->card_id] ?? ''}}" card-id="{{$v->card_id ?? ''}}">
				<div class="box">
					<img src="{{$v->card_img}}" class="{{$v->card_status==0?'monochrome':''}}">
					<div class="box-content">
						@if(is_array($v->range_text))
						<ul class="range_sign_ul">
							@foreach($v->range_text as $t)
							<li class="range_sign_li">
								<span>{{$t}}</span>
							</li>
							@endforeach
						</ul>
						@else
						<div class="range_sign">
								<span>{{$v->range_text}}</span>
							</div>
						@endif
						<h3 class="title">{{$v->card_name}}</h3>
						<span class="post">销量：{{$v->card_sales}}</span>
						<ul class="icon">
							<li><a href="#" data-toggle="modal" data-target="#exampleModal" data-cardid="{{$v->card_id}}"><i class="lnr lnr-pencil"></i></a></li>
						</ul>
					</div>
				</div>
			</div>
			@endforeach
		</div>
	</div>
	<!-- END BASIC TABLE -->
	@endif
	
	@if($downcards->count()>0)
	<!-- BASIC TABLE -->
	<div class="panel">
		<div class="panel-heading">
			<h3 class="panel-title">停售饭卡</h3>
		</div>
		<div class="panel-body">
		    @foreach($downcards as $k=>$v)
		    <div class="col-md-4 col-sm-6 card-relist">
				<div class="box">
					<img src="{{$v->card_img}}" class="{{$v->card_status==0?'monochrome':''}}">
					<div class="box-content">
						<h3 class="title">{{$v->card_name}}</h3>
						<span class="post">销量：{{$v->card_sales}}</span>
						<ul class="icon">
							<li><a href="###" data-toggle="modal" data-target="#exampleModal" data-cardid="{{$v->card_id}}" style="display: inline-block;"><i class="lnr lnr-pencil"></i></a><a  style="display: inline-block;" href="###" data-cardid="{{$v->card_id}}" onclick="delcard(this)"><i class="lnr lnr-trash"></i></a></li>
						</ul>
					</div>
				</div>
			</div>
			@endforeach
		</div>
	</div>
	<!-- END BASIC TABLE -->
	@endif
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">更改饭卡规则</h4>
      </div>
      <form action="/updateCardAction" method="post" enctype="multipart/form-data" id="EditCardInfoForm">
      <div class="modal-body">
          <div class="form-group">
            <label class="control-label">名称</label>
			<input type="text" name="cardname" value="" class="form-control form-input-control" placeholder="饭卡名称" alt="饭卡名称">
			
			<label class="control-label">业务类型</label>
				<label class="fancy-radio form-input-control">
					<input name="business_type" value="ZH" type="radio">
					<span></span>
				</label>
			<div class="limitdaynum hide">
				<label class="control-label">限制天数</label>
				<input type="number" name="limitday" readonly unselectable="on" AUTOCOMPLETE="off" value="" class="form-control limit_days form-input-control" alt="限制天数" placeholder="时间内可用，超时作废">
			</div>
			<div class="groupcard hide">
				<label class="control-label">组合次数</label>
				<input type="number" name="num_198" readonly unselectable="on" value="" min="0" AUTOCOMPLETE="off" class="form-control groupnum form-input-control" alt="198次数" placeholder="198套餐在组合卡中可用次数">
				<input type="number" name="num_258" readonly unselectable="on" value="" disabled="disabled" min="0" AUTOCOMPLETE="off" class="form-control groupnum form-input-control" alt="258次数" placeholder="258套餐在组合卡中可用次数">
				<input type="number" name="num_298" readonly unselectable="on" value="" disabled="disabled" min="0" AUTOCOMPLETE="off" class="form-control groupnum form-input-control" alt="298次数" placeholder="298套餐在组合卡中可用次数">
			</div>

			<label class="control-label">开始可用时间，每天的</label>
			<input type="time" name="starttime" class="form-control form-input-control" alt="开始可用时间">
			
			<label class="control-label">结束可用时间，每天的</label>
			<input type="time" name="stoptime" class="form-control form-input-control" alt="结束可用时间">
			
			<label class="control-label">可消费的最高餐品价格</label>
			<input type="text" name="mealprice" class="form-control form-input-control" placeholder="可消费的最高餐品价格" alt="可消费的最高餐品价格">
			
			<label class="control-label">可用次数</label>
			<input type="number" name="frequency" class="form-control form-input-control" placeholder="该卡的全部可用次数" alt="可用次数">
			
			<label class="control-label">每日可用次数</label>
			<input type="number" name="once" value="1" class="form-control form-input-control" placeholder="每日可用次数" alt="每日可用次数">
			
			<label class="control-label">出售价格</label>
			<input type="text" name="price" value="" class="form-control form-input-control" placeholder="饭卡出售价格" alt="饭卡出售价格">

			<label class="control-label">是否开启活动价</label>
			<div class="switch form-input-control" data-on-label="开" data-off-label="关">
			    <input type="checkbox" name="huodong_state" value="" />
			    <input type="hidden" name="activity_price_select" value="">
			</div>

			<div class="activity_price hide">
				<label class="control-label">活动价格</label>
				<input type="text" name="activity_price" value="0" class="form-control form-input-control" placeholder="饭卡出售活动价格" alt="饭卡出售活动价格">
			</div>

			<label class="control-label">饭卡描述</label>
			<textarea name="desc" class="form-control form-input-control" placeholder="描述一下饭卡使用规则"></textarea>

			<label class="control-label">发布范围</label>
			<br>
				<label class="">
					<input name="range_id" value="0" type="radio">
					<span>全范围</span>
				</label>
				<br>
				@foreach($circles as $k=>$v)
				<label class="">
					<input name="range_id[]" value="{{$v->circle_id}}" type="checkbox">
					<span>{{$v->circle_name}}</span>
				</label>
				<br>
				@endforeach
				<br>
			<label class="control-label">背景图</label>
			<img src="" class="loadCardBackground">
			<input type="file" name="mealcardBackground" class="form-input-control" alt="背景图">

			<label class="control-label">是否在售</label>
			<div class="switch form-input-control" data-on-label="在售" data-off-label="下架">
			    <input type="checkbox" name="cardstatus_state" value="" />
			    <input type="hidden" name="cardstatus" value="">
			</div>
			<label class="control-label">是否免配送费</label>
			<div class="switch form-input-control" data-on-label="免费" data-off-label="收费">
			    <input type="checkbox" name="delivery_free_state" value="" />
			    <input type="hidden" name="delivery_free" value="">
			</div>
          </div>
          <input type="hidden" name="cardid" value="">
          <input type="hidden" name="circle_id" value="0">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary confirmeditCard" >修改设置</button>
      </div>
      </form>
    </div>
  </div>
</div>
@endsection

@section('js-import')
<script src="{{config('app.inlet_src')}}assets/scripts/Sortable.min.js"></script>
@endsection

@section('js-write')
<script type="text/javascript">
	$('.circle_select').change(function(){
		$('#exampleModal').find('input[name="circle_id"]').val($(this).val());
	});
	Sortable.create(document.getElementById('cards_list'),{
        animation: 500, //动画参数
        onEnd: function(evt){ //拖拽完毕之后发生该事件
              var id_arr='';
              var card_id = '';
              for(var i=0, len=evt.from.children.length; i<len; i++){
                 id_arr+=','+ evt.from.children[i].getAttribute('drag-id');
                 card_id+=','+ evt.from.children[i].getAttribute('card-id');
              }
              id_arr=id_arr.substr(1);
              card_id=card_id.substr(1);
              $.ajaxSetup({
				    headers: {
				        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
				    }
			  });
			  $.post('/card-sort',{'list':id_arr,'cards':card_id},function(respose){
			  	console.log(respose);
			  });
              //然后请求后台ajax 这样就完成了拖拽排序
             console.log(id_arr);
         }
    });
	
	$('#exampleModal').on('show.bs.modal', function (event) {
	  var button = $(event.relatedTarget) // Button that triggered the modal
	  var cardid = button.data('cardid') // Extract info from data-* attributes
	  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
	  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
	  var modal = $(this);
	  modal.find('.form-input-control').val('');
	  modal.find('.loadCardBackground').attr('src','');
	  modal.find('input[type="text"]').val('');
	  modal.find('input[type="time"]').val('');
	  modal.find('input[type="number"]').val('');
	  $.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
	  });
	  $.post('/getcard-info',{'card_id':cardid},getcardinfo);
	  modal.find('input:radio[name="business_type"]').change(checkedBusiness);
	  modal.find('.groupnum').bind('input propertychange',changeVal);
	});
	// 饭卡业务类型
	var card_type = ['SJ','CK','XS','ZH'];
	var card_type_text = ['跟随时间递减','次数卡','限时卡','组合卡'];
	var subStr= /&&&/ig;
	var card_activity = ['SE','CE'];
	var card_status_de = ['XJ','SJ'];
	var delivery_status_de = ['SF','MF'];
	function getcardinfo(response){
		var card = response.card;
		var activityAct = {};
		$('input[name="cardname"]').val(card.card_name);
		$('input[name="business_type"]').val(card_type[card.type]).next().html("<i></i>"+card_type_text[card.type]);
	  	$('input:radio[name="business_type"][value="'+card_type[card.type]+'"]').attr('checked','checked').trigger('change');
		$('input[name="limitday"]').val(card.card_frequency);
		$('input[name="num_198"]').val(card.num_198);
		$('input[name="num_258"]').val(card.num_258);
		$('input[name="num_298"]').val(card.num_298);
		$('input[name="starttime"]').val(card.start_time);
		$('input[name="stoptime"]').val(card.stop_time);
		$('input[name="mealprice"]').val(card.meal_max_price);
		$('input[name="frequency"]').val(card.num);
		$('input[name="once"]').val(card.day_once);
		$('input[name="price"]').val(card.card_price);
		$('textarea[name="desc"]').val(card.card_desc.replace(subStr,"\r\n"));
		$('.loadCardBackground').attr('src',card.card_img);
		var is_activity = card.card_activity_price>0;
		var is_cardstatus_state = card.card_status==1;
		activityAct.onText = "开";
		activityAct.offText = "关";
		activityAct.onSwitchChange = function(event,state){
			if(state==true){
				$('.activity_price').removeClass('hide');
			}else{
				$('.activity_price').addClass('hide');
				$('input[name="activity_price"]').val(0);
			}
		};
		$('input:checkbox[name="range_id[]"]').removeAttr('checked')
		$('input:radio[name="range_id"]').removeAttr('checked')	
		if(card.range_id == 0){
			$('input:radio[name="range_id"][value="0"]').attr('checked','checked').trigger('click');
		}else{
			var range_ids = card.range_id.split(',');
			for (var i = range_ids.length - 1; i >= 0; i--) {
				// range_ids[i]
				console.log(range_ids[i]);
				$('input:checkbox[name="range_id[]"][value="'+range_ids[i]+'"]').attr('checked','checked').trigger('click');
			}
		}
		
		// var clonelabel = $('.sendrange_label').clone();
		//activity_price_select - cardstatus
		$("[name='huodong_state']").bootstrapSwitch(activityAct);
		$("[name='huodong_state']").bootstrapSwitch('state', is_activity);
		$("[name='huodong_state']").val(Number(is_activity));
		$('[name="activity_price_select"]').val(card_activity[Number(is_activity)]);
		$("[name='cardid']").val(card.card_id);

		$("input:checkbox[name='cardstatus_state']")
		.val(Number(is_cardstatus_state));
		$('[name="cardstatus"]').val(card_status_de[Number(is_cardstatus_state)]);

		$("[name='cardstatus_state']").bootstrapSwitch({
			onText:"在售",
			offText:"下架",
			onSwitchChange:function(event,state){
				$("[name='cardstatus_state']").val(Number(state));
				$('[name="cardstatus"]').val(card_status_de[Number(state)]);
			}
		});
		$("[name='cardstatus_state']").bootstrapSwitch('state', is_cardstatus_state);

		$("input:checkbox[name='delivery_free_state']")
		.val(Number(card.delivery_free));
		$('[name="delivery_free"]').val(delivery_status_de[Number(card.delivery_free)]);

		$("[name='delivery_free_state']").bootstrapSwitch({
			onText:"免费",
			offText:"收费",
			onSwitchChange:function(event,state){
				$("[name='delivery_free_state']").val(Number(state));
				$('[name="delivery_free"]').val(delivery_status_de[Number(state)]);
			}
		});
		$("[name='delivery_free_state']").bootstrapSwitch('state', card.delivery_free);


		$('input[name="activity_price"]').val(card.card_activity_price);
	}

	$('input[type=file][name=mealcardBackground]').change(function(e){
		var files = e.target.files;
		var v = $(this).val();
		var reader = new window.FileReader();
		reader.readAsDataURL(files[0]);
		//异步加载文件成功
	    reader.onload = function(e){
	       // reader.result 表示图片地址
	       $('.loadCardBackground').attr('src',reader.result);
	    }
	});

	function changeVal(){
		var num198 = Number($('input[name="num_198"]').val());
		var num258 = Number($('input[name="num_258"]').val());
		var num298 = Number($('input[name="num_298"]').val());
		$('input[name="frequency"]').val(num198+num258+num298);
	}

	function checkedBusiness(){
		var value = $(this).val();
		if(value=='XS'){
			$('.limitdaynum').removeClass('hide');
			$('.groupcard').hasClass('hide')?'':$('.groupcard').addClass('hide');
		}else if(value=='ZH'){
			$('.groupcard').removeClass('hide');
			$('.limitdaynum').hasClass('hide')?'':$('.limitdaynum').addClass('hide');
		}else{
			$('.limitdaynum').hasClass('hide')?'':$('.limitdaynum').addClass('hide');
			$('.groupcard').hasClass('hide')?'':$('.groupcard').addClass('hide');
		}
	}

	var SendParam = {'dataType':'json'};

	SendParam.beforeSubmit = function(formData, jqForm, options){
	    for (var i = 0; i < formData.length; i++) {
	        var t = $('input[name="'+formData[i].name+'"]').attr('alt');
	        if(formData[i].value==''){
	            if(formData[i].type=='file'||formData[i].type=='checkbox'){
	                continue;
	            }else{
	                var nameV = formData[i].name;
	                if(nameV!='limitday'&&nameV!='num_198'&&nameV!='num_258'&&nameV!='num_298'){
	                    toastr.error('请填写'+t+'！');
	        			console.log(formData[i].name);
	                    return false;
	                }
	                if(nameV=='limitday'&&$('input[name="business_type"]:checked').val()=='XS'){
	                    toastr.error('请填写'+t+'！');
	                    console.log(formData[i].name);
	                    return false;
	                }
	                if($('input[name="business_type"]:checked').val()=='ZH'&&nameV=='num_198'&&nameV=='num_258'&&nameV=='num_298'){
	                    toastr.error('请填写'+t+'！');
	                    console.log(formData[i].name);
	                    return false;
	                }
	            }
	        }
	        if(!$('input[name="business_type"]:checked').val()){
	            toastr.error('请选择卡的类型！');
	            return false;
	        }
	    }
	};

	SendParam.success = function(response) {
		console.log(response);
		if(response.success){
	        setTimeout(function(){
	            location.href = '/manageCard';
	        },2000);
			toastr.success(response.message);
		}else{
			toastr.error('修改失败，请联系开发人员！');
		}
	};

	SendParam.error = function(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==422){
			var RegError = XMLHttpRequest.responseJSON.errors;
			for(var o in RegError){
				for (var i = 0; i < RegError[o].length; i++) {
					toastr.error(RegError[o][i]);
				}
			}
		}
	};

	ajaxForm_('#EditCardInfoForm',SendParam);


	function delcard(this_){
		var cardid = $(this_).attr('data-cardid');
		$.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
	    });
	    $.post('/card/delete',{'cardid':cardid},function(response){
	    	if(response.success){
	    		$(this_).parents('.card-relist').remove()
	    		toastr.success(response.message);
	    	}else{
	    		toastr.error(response.message);
	    	}
	    });

	}

</script>
@endsection